package com.bignerdranch.android.geoquiz

import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import java.lang.Exception
import kotlin.math.absoluteValue
private const val TAG="MainActivity"
private const val KEY_INDEX="index"
private const val REQUEST_CODE_CHEAT=0
private val  Second_BUG:String="Second Bug" //页面旋转bug
private val Third_BUG:String="Third_Bug"

class MainActivity : AppCompatActivity()
{
    private lateinit var trueButton:Button
    private lateinit var falseButton:Button
    private lateinit var nextButton:Button
    private lateinit var previousButton: Button
    private lateinit var questionTextView: TextView
    private lateinit var cheatButton: Button
    private lateinit var scoreView:TextView
    private lateinit var cheat_text_view:TextView





    private val quizViewModel:QuizViewModel by lazy {
        ViewModelProviders.of(this).get(QuizViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG,"onCreate(Bundle?) called")
        setContentView(R.layout.activity_main)
        if (savedInstanceState!=null)
        {
         quizViewModel.mIsCheat[quizViewModel.currentIndex]=savedInstanceState.getBoolean(Second_BUG,false)

        }


        val currentIndex=savedInstanceState?.getInt(KEY_INDEX,0)?:0
        quizViewModel.currentIndex=currentIndex
        trueButton=findViewById(R.id.true_button)
        falseButton=findViewById(R.id.false_button)
        nextButton = findViewById(R.id.next_button)
        cheatButton=findViewById(R.id.cheat_button)
        previousButton=findViewById(R.id.previous_button)
        questionTextView=findViewById(R.id.question_text_view)
        scoreView=findViewById(R.id.score_view)
        cheat_text_view=findViewById(R.id.cheat_number)


//1.trueButton
        trueButton.setOnClickListener{view:View->
            checkAnswer(true)
            quizViewModel.answerQuestion()
            checkIsanswered()
        }


//2.falseButton
        falseButton.setOnClickListener{view:View->
           checkAnswer(false)
            quizViewModel.answerQuestion()
            checkIsanswered()
        }
//3. nextButton
        nextButton.setOnClickListener{
//            currentIndex=(currentIndex+1)%questionBank.size
//            val questionTextResId=questionBank[currentIndex].textResId
//            questionTextView.setText(questionTextResId)
            quizViewModel.moveToNext()
            updateQuestion()
            checkIsanswered()
        }

//4.previousButton
        previousButton.setOnClickListener {
            quizViewModel.moveToPrev()
            updateQuestion()
            checkIsanswered()
        }

 //5.TextView
        questionTextView.setOnClickListener{
            quizViewModel.moveToNext()
            updateQuestion()
        }

  //6.cheatButton
        cheatButton.setOnClickListener {
            //Start CheatActivity
//            val intent=Intent(this,CheatActivity::class.java)
            val answerIsTrue=quizViewModel.currentQuestionAnswer
            val intent=CheatActivity.newIntent(this@MainActivity,answerIsTrue)

//            startActivity(intent)
            quizViewModel.cheat()
            startActivityForResult(intent, REQUEST_CODE_CHEAT)

        }

        updateQuestion()
        checkIsanswered()
    }

    override fun onStart() {
        super.onStart()
        Log.d(TAG,"onStart() called")
        scoreView.setText((quizViewModel.score).toString())
        cheat_text_view.setText("还剩作弊次数：\u3000"+(quizViewModel.cheatNumber).toString())
        cheatControl()
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG,"onResume() called")

    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG,"onPause() called")

    }








    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode!=Activity.RESULT_OK)
        {
            return
        }
        if (requestCode== REQUEST_CODE_CHEAT)
        {
            quizViewModel.isCheater=data?.getBooleanExtra(EXTRA_ANSWER_SHOWN,false)?:false
        }
    }



    override fun onSaveInstanceState(savedInstanceState: Bundle) {
        super.onSaveInstanceState(savedInstanceState)
        Log.i(TAG,"onSaveInstanceState")
        savedInstanceState.putInt(KEY_INDEX,quizViewModel.currentIndex)
        savedInstanceState.putBoolean(Third_BUG,quizViewModel.mIsCheat[quizViewModel.currentIndex])
    }

    override fun onStop() {
        super.onStop()
        Log.d(TAG,"onStop() called")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG,"onDestroy() called")
    }

    private fun updateQuestion(){
        val questionTextResId = quizViewModel.currentQuestionText
        questionTextView.setText(questionTextResId)
    }

    private fun cheatControl()
    {
        if (quizViewModel.cheatNumber>=1)
        {
            cheatButton.isEnabled=true
        }
        else{
            cheatButton.isEnabled=false
        }
    }

    private fun checkAnswer(userAnswer:Boolean)
    {
        //计算得分
        val correctAnswer=quizViewModel.currentQuestionAnswer
        if (userAnswer==correctAnswer)
        {
            quizViewModel.winScore()
        }
        else
        {
            quizViewModel.loseScore()
        }
       scoreView.setText((quizViewModel.score).toString())

        ///////////////////////////////
        /*val messageResId= if (userAnswer==correctAnswer)
        {
            R.string.correct_toast
        }
        else
        {
            R.string.incorrect_toast
        }*/

           val messageResId=when{
               quizViewModel.isCheater->R.string.judgment_toast
               userAnswer==correctAnswer->R.string.correct_toast
               else->R.string.incorrect_toast
           }
           val toast = Toast.makeText(this,messageResId,Toast.LENGTH_SHORT)
           toast.setGravity(Gravity.TOP,0,0)
           toast.show()

    }
    private fun checkIsanswered()
    {
        val currentisanswered=quizViewModel.currentIsanswered
        if (currentisanswered)
        {
            trueButton.isEnabled=false
            falseButton.isEnabled=false
        }
        else
        {
            trueButton.isEnabled=true
            falseButton.isEnabled=true
        }
    }

}